﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using personalplaner.business;
using personalplaner.business.stamm;
using personalplaner.common.mvvm;
using personalplaner.common.mvvm.commands;
using personalplaner.servicemodel.dataaccess;


namespace personalplaner.gui.stamm.viewmodels
{
    public class EditDaysInMonthViewModel : BaseViewModel
    {
		public EditDaysInMonthViewModel(DependencyObject parent)
            : base(parent)
        {
        }

		public override void Loaded()
		{
			var mw = GetService<IMainWindowDisplayContainer>();
			mw.IsWaitVisible = false;
		}

		public void SelectMonth(int atid)
		{
			foreach (var itm in MonthList)
			{
				if (itm.AtId == atid)
				{
					SelectedMonth = itm;
					return;
				}
			}
		}

        #region Commands

        ICommand _okcommand;
        public ICommand OkCommand
        {
            get
            {
                if (_okcommand == null)
                    _okcommand = new RelayCommand(OnOkCommand);
                return _okcommand;
            }
        }

        private void OnOkCommand(object parameter)
        {
			var da = GetService<ICommonDataAccess>();
			foreach (var itm in MonthList)
			{
				da.SaveMonthDays(itm.AtId, itm.Tage);
			}


        	var wnd = Parent as Window;
			if (wnd != null)
			{
				wnd.DialogResult = true;
				wnd.Close();
				return;
			}

			var mw = GetService<IMainWindowDisplayContainer>();
			mw.MoveToPreviousView();
        }

        ICommand _cancelcommand;
        public ICommand CancelCommand
        {
            get
            {
                if (_cancelcommand == null)
                    _cancelcommand = new RelayCommand(OnCancelCommand);
                return _cancelcommand;
            }
        }

        private void OnCancelCommand(object parameter)
        {
			var wnd = Parent as Window;
			if (wnd != null)
			{
				wnd.DialogResult = false;
				wnd.Close();
				return;
			}

			var mw = GetService<IMainWindowDisplayContainer>();
			mw.MoveToPreviousView();
        }

		#endregion

        #region Properties

		IList<PlanMonth> _monthList;
		public IList<PlanMonth> MonthList
		{
			get
			{
				if (_monthList == null)
				{
					var da = GetService<ICommonDataAccess>();
					var lst = da.GetActiveMonths();
					_monthList = lst != null ? new List<PlanMonth>(lst) : new List<PlanMonth>();
				}

				if (_monthList != null && _monthList.Count >= DateTime.Now.Month)
					SelectedMonth = _monthList[DateTime.Now.Month - 1];

				return _monthList;
			}
		}

		PlanMonth _selectedMonth;
		public PlanMonth SelectedMonth
		{
			get { return _selectedMonth; }
			set
			{
				_selectedMonth = value;
				RaisePropertyChanged("SelectedMonth");
			}
		}

        #endregion
    }
}
